package com.qk.ezbuy.controller;

import com.qk.ezbuy.pojo.User;
import com.qk.ezbuy.service.UserService;
import com.qk.ezbuy.util.Myutil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import java.util.*;
import java.util.concurrent.TimeUnit;

@RestController
public class LoginController {

    @Autowired
    private UserService userService;

    @Autowired
    private RedisTemplate redisTemplate;

    @RequestMapping("/login")
    public String login(User user, HttpServletRequest request) {
        User userx = userService.selectByLoginName(user.getLoginname());
        String password = Myutil.md5(user.getPassword());
        if (userx != null && userx.getPassword().equals(password)) {
            String uuid = UUID.randomUUID().toString();
            //用户登陆状态
            redisTemplate.opsForValue().set(uuid, userx, 30 * 60, TimeUnit.SECONDS);
            return uuid;
        }
        return "false";
    }

    @RequestMapping("/loginget")
    public User getUser(String uuid) {
        User user = null;
        if (uuid != "" && uuid != null) {
            if (redisTemplate.hasKey(uuid)) {
                user = (User) redisTemplate.opsForValue().get(uuid);
            }
        }
        return user;
    }
    @RequestMapping("/loginout")
    public void loginout (String uuid){
        redisTemplate.delete(uuid);
    }
}
